<?php

namespace App\Helpers;

/**
 *
 * @author qfh
 */
class Utils
{
    //检测身份证正确
    public static  function IdCard($value)
    {
        $value = strtoupper(trim($value));
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if (!preg_match($regx, $value))
        {
            return FALSE;
        }
        if (15 == strlen($value))
        { //检查15位
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";
            @preg_match($regx, $value, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
            if (!strtotime($dtm_birth))
            {
                return FALSE;
            } else
            {
                return TRUE;
            }
        } else
        {           //检查18位
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $value, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
            if (!strtotime($dtm_birth))
            {  //检查生日日期是否正确
                return FALSE;
            } else
            {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $sign = 0;
                for ($i = 0; $i < 17; $i++)
                {
                    $b = (int) $value{$i};
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($value, 17, 1))
                {
                    return FALSE;
                } else
                {
                    return TRUE;
                }
            }
        }
        return false;
    }

    /**
     *  根据身份证号码获取性别
     *  @param string $idcard     身份证号码
     *  @return int   $sex(性别)  1(男) 2(女)
     */
    public static function getsexbyidcard($idcard) {
        if(empty($idcard)) return false;
        $sexint = (int) substr($idcard, 16, 1);
        return $sexint % 2 === 0 ? 2 : 1;
    }

    /**
     *  根据身份证号码获取出生年月
     *  @param  string $idcard    身份证号码
     *  @return string $birthday  出生年月
     */
    public static function getbirthdaybyidcard($idcard) {
        if(empty($idcard)) return false;
        $bir   = substr($idcard, 6, 8);
        $year  = substr($bir, 0, 4);
        $month = substr($bir, 4, 2);
        $day   = substr($bir, 6, 2);
        return $year . "-" . $month . "-" . $day;
    }


    /**
     * 获取浏览器名称
     * @return string
     */
    public static function getBrowser()
    {
        $agent = $_SERVER["HTTP_USER_AGENT"];
        //ie11判断
        if (strpos($agent, 'MSIE') !== false || strpos($agent, 'rv:11.0')) {
            return "ie";
        } else if (strpos($agent, 'Firefox') !== false) {
            return "firefox";
        } else if (strpos($agent, 'Chrome') !== false) {
            return "chrome";
        } else if (strpos($agent, 'Opera') !== false) {
            return 'opera';
        } else if ((strpos($agent, 'Chrome') == false) && strpos($agent, 'Safari') !== false) {
            return 'safari';
        } else if (strpos($agent, 'MicroMessenger') !== false) {
            return 'wechat';
        } else {
            return true;
        }
    }

    /**
     * 获取浏览器版本
     * @return string
     */
    public static function getBrowserVer()
    {
        $agent = $_SERVER['HTTP_USER_AGENT'];
        if (preg_match('/MSIE\s(\d+)\..*/i', $agent, $regs)) {
            return true;
        } elseif (preg_match('/FireFox\/(\d+)\..*/i', $agent, $regs)) {
            return true;
        } elseif (preg_match('/Opera[\s|\/](\d+)\..*/i', $agent, $regs)) {
            return true;
        } elseif (preg_match('/Chrome\/(\d+)\..*/i', $agent, $regs)) {
            return true;
        } elseif ((strpos($agent, 'Chrome') == false) && preg_match('/Safari\/(\d+)\..*$/i', $agent, $regs)) {
            return true;
        } elseif (preg_match('/MicroMessenger\/(\d+)\..*/i', $agent, $regs)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断是否微信浏览器
     * @return type
     */
    public static function isWechatBrowser()
    {
        $agent = $_SERVER['HTTP_USER_AGENT'];
        return (strpos($agent, "MicroMessenger") !== false);
    }

    /**
     * 获取访问域名
     * @return type
     */
    public static function getHostUrl($request_url = null)
    {
        $request_url = empty($request_url) ? 'http://localhost' : $request_url;
        $parsed_url  = parse_url($request_url);
        $scheme      = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
        $host        = isset($parsed_url['host']) ? $parsed_url['host'] : '';
        $port        = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
        return "$scheme$host$port";
    }

    /**
     * 获取IP地址
     */
    public static function ipAddress()
    {
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $cip = $_SERVER["HTTP_CLIENT_IP"];
        } elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
            $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } elseif (!empty($_SERVER["REMOTE_ADDR"])) {
            $cip = $_SERVER["REMOTE_ADDR"];
        } else {
            $cip = "127.0.0.1";
        }
        return $cip;
    }

    /**
     * @abstract 获取html代码中的img的src
     * @return array
     */
    public static function getHtmlImageSrc($html)
    {
        if (!$html)
            return array();

        $preg_partern = '/<img.+?src=\"?(.+?\.(jpg|gif|bmp|bnp|png))\"?.+?>/i';
        $match        = array();
        preg_match_all($preg_partern, $html, $match);
        return $match[1];
    }

    /**
     * @abstract 替换html代码里面的img标签
     * @param type $html
     * @param type $replace default ''
     * @return string
     */
    public static function replaceHtmlImage($html, $replace = '')
    {
        if (!$html)
            return '';

        $preg_partern = '/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+?>/i';
        return preg_replace($preg_partern, $replace, $html);
    }

    /**
     * 生成随机密码
     */
    public static function createPassword($pw_length = 8)
    {
        $randpwd = '';
        for ($i = 0; $i < $pw_length; $i++) {
            $randpwd .= chr(mt_rand(48, 122));
        }
        return $randpwd;
    }

    /**
     * 计算字utf8符长度
     */
    public static function utf8StrLen($str)
    {
        $count = 0;
        for ($i = 0; $i < strlen($str); $i++) {
            $value = ord($str[$i]);
            if ($value > 127) {
                $count++;
                if ($value >= 192 && $value <= 223) {
                    $i++;
                } elseif ($value >= 224 && $value <= 239) {
                    $i = $i + 2;
                } elseif ($value >= 240 && $value <= 247) {
                    $i = $i + 3;
                } else {

                }
            }
            $count++;
        }
        return $count;
    }

    /**
     * 去除特殊符号
     */
    public static function removeSpe($string = "")
    {
        $string  = htmlspecialchars_decode($string);
        $search  = array("\\\"");
        $replace = array("\"");
        return str_replace($search, $replace, $string);
    }

    /**
     * 删除HTML标签
     */
    public static function removeHTML($string = "")
    {
        $string  = html_entity_decode($string, ENT_COMPAT, 'UTF-8');
        $string  = stripslashes($string);
        $string  = strip_tags($string);
        $search  = array(" ", "　", "\t", "\n", "\r");
        $replace = array("", "", "", "", "");
        return str_replace($search, $replace, $string);
    }

    /**
     * @desc    判断用户使用的是ios  还是android
     */
    public static function version()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $version    = 0;
        if (strpos($user_agent, 'iPhone') || strpos($user_agent, 'iPad') || strpos($user_agent, 'iPod')) {
            $version = 1;
        } elseif (strpos($user_agent, 'Android')) {
            $version = 6;
        } elseif (strpos($user_agent, 'MicroMessenger')) {
            $version = 8;
        }
        return $version;

    }

    /**
     * @param $param
     * @return string
     * 去除字符串中的空格
     */
    public static function removeSpace($param)
    {
        return isset($param) ? str_replace(" ", "", $param) : '';
    }

    /*
     * 获取手机浏览器版本
     */
    public static function getMobileBrowser()
    {
        $useragent = $_SERVER["HTTP_USER_AGENT"];

        function CheckSubstrs($substrs,$text){
            foreach($substrs as $substr)
                if(false!==strpos($text,$substr)){
                    return true;
                }
            return false;
        }

        $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');

        return CheckSubstrs($mobile_token_list,$useragent);

    }

    /*
     * 获取是否为移动端
     */
    public static function getMobileOs()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
        {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
        {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT']))
        {
            $clientkeywords = array ('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
            {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT']))
        {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
            {
                return true;
            }
        }
        return false;
    }

    /**
     * 生成各种流水单号
     *
     * @param int $action_code
     * @return bool|string
     */
    public static function createNid($action_code = '1001')
    {
        /**
         * 格式: 当前日期+动作码+当前时间戳最后5位+10位随机数
         * 长度: 27位
         * 动作码对照:
         *      1001 : 提现
         */
        $nid = date('Ymd');
        $nid .= strval($action_code);
        $nid .= substr(time(), 5, 9);
        $nid .= mt_rand(1000000000, 9999999999);

        return $nid;
    }

    /**
     * 根据用户ID,获取用户唯一邀请码
     * 格式:公司门牌号 + 用户ID
     * 长度:不固定
     * @param $user_id
     * @return int
     */
    public static function getInviteCode($user_id)
    {
        return (1902 + (int)$user_id);
    }

    //判断是否是正确的邀请码

    public static  function isInviteCode($invite_code)
    {
        //首先判断邀请码是否为数字
        if(is_numeric($invite_code))
        {
            //初步判断是否正确
            if($invite_code - 1902 > 0){
                return true;
            }else{
                return false;
            }
        }
        return false;
    }


    //通过ip获取地理位置
    public static  function getLocation()
    {
        $ip = self::ipAddress();
        $res = @file_get_contents("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=".$ip);
        $jsonMatches = array();
        preg_match('#\{.+?\}#', $res, $jsonMatches);
        if(!isset($jsonMatches[0])){ return ''; }
        $json = json_decode($jsonMatches[0], true);
        if(isset($json['ret']) && $json['ret'] == 1){
            $json['ip'] = $ip;
            unset($json['ret']);
        }else{
            return '';
        }

        return $json["province"].$json['city'];
    }

    //生成双色球随机号
    public static function randDouble()
    {
        $red  = array("01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33");
        $blue = array("01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16");

        shuffle($red);
        shuffle($blue);

        for($i=0;$i<6;$i++){
            $key = array_rand($red);
            $try[] = $red[$key];
            unset($red[$key]);
        }
        sort($try);
        return implode(',',$try).'#'.$blue[array_rand($blue)];

    }

    
}
